
/*
# ============================================================================
# 版权所有 Chilcoo.com，并保留所有权利。
# 网站地址: http://www.chilcoo.com/ccerp
# ----------------------------------------------------------------------------
# 这不是一个自由软件！你不能通过任何方式破解本软件.
# 使用:不允许对程序代码以任何形式任何目的的再发布。
# ============================================================================
# $Author: Chilcoo Inc. *
# $Official website  : www.chilcoo.com
# オーダー処理のページ
# 
# 開発日記：
# 2011－04－15
# ただいま購入用の基本データーの処理は一部完了しました。
# カートの処理と確認ビュー及びバックのAJAX処理はまだ完成していません。
*/
ajax_callback_page = '<{$ROOTPATH}>/_manager/pro/default.php';


var swf_upload = {
	/* Demo Note:  This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
	The FileProgress class is not part of SWFUpload.
	*/


	/* **********************
	   Event Handlers
	   These are my custom event handlers to make my
	   web application behave the way I went when SWFUpload
	   completes different tasks.  These aren't part of the SWFUpload
	   package.  They are part of my application.  Without these none
	   of the actions SWFUpload makes will show up in my application.
	   ********************** */
	swfUploadPreLoad:function () {
		var self = this;
		var loading = function () {
			//document.getElementById("divSWFUploadUI").style.display = "none";
			document.getElementById("divLoadingContent").style.display = "";

			var longLoad = function () {
				document.getElementById("divLoadingContent").style.display = "none";
				document.getElementById("divLongLoading").style.display = "";
			};
			this.customSettings.loadingTimeout = setTimeout(function () {
					longLoad.call(self)
				},
				15 * 1000
			);
		};
		
		this.customSettings.loadingTimeout = setTimeout(function () {
				loading.call(self);
			},
			1*1000
		);
	},
	swfUploadLoaded:function () {
		var self = this;
		clearTimeout(this.customSettings.loadingTimeout);
		//document.getElementById("divSWFUploadUI").style.visibility = "visible";
		//document.getElementById("divSWFUploadUI").style.display = "block";
		document.getElementById("divLoadingContent").style.display = "none";
		document.getElementById("divLongLoading").style.display = "none";
		document.getElementById("divAlternateContent").style.display = "none";
		
		//document.getElementById("btnBrowse").onclick = function () { self.selectFiles(); };
		document.getElementById("btnCancel").onclick = function () { self.cancelQueue(); };
	},
	   
	swfUploadLoadFailed:function () {
		clearTimeout(this.customSettings.loadingTimeout);
		//document.getElementById("divSWFUploadUI").style.display = "none";
		document.getElementById("divLoadingContent").style.display = "none";
		document.getElementById("divLongLoading").style.display = "none";
		document.getElementById("divAlternateContent").style.display = "";
	},
	   
	   
	fileQueued:function (file) {
		try {
			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setStatus("アップロード待機中です...");
			progress.toggleCancel(true, this);

		} catch (ex) {
			this.debug(ex);
		}

	},

	fileQueueError:function (file, errorCode, message) {
		try {
			if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
				alert("選択したファイル数が多すぎます.\n" + (message === 0 ? "アップロード制限に達しています." : "選択ファイル数は" + (message > 1 ? message + "個以下にしてください." : "1ファイルにしてください.")));
				return;
			}

			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setError();
			progress.toggleCancel(false);

			switch (errorCode) {
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				progress.setStatus("ファイルサイズが大きすぎます");
				this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				progress.setStatus("0バイトのファイルはアップロードできません");
				this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				progress.setStatus("無効なファイルタイプです");
				this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			default:
				if (file !== null) {
					progress.setStatus("不明なエラーです");
				}
				this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			}
		} catch (ex) {
	        this.debug(ex);
	    }
	},

	fileDialogComplete:function (numFilesSelected, numFilesQueued) {
		try {
			if (numFilesSelected > 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = false;
				document.getElementById(this.customSettings.cancelButtonId).className = "btn-cancel";
			}
			
			/* I want auto start the upload and I can do that here */
			// this.startUpload();
	        var uploadbutton = document.getElementById("btnUpload");
	        uploadbutton.className = "btn-upload";
	        uploadbutton.disabled = "";
	        document.getElementById("uploadStatus").innerHTML = "「アップロード開始」ボタンをクリックしてください";
		} catch (ex)  {
	        this.debug(ex);
		}
	},

	uploadStart:function (file) {
		try {
			/* I don't want to do any file validation or anything,  I'll just update the UI and
			return true to indicate that the upload should start.
			It's important to update the UI here because in Linux no uploadProgress events are called. The best
			we can do is say we are uploading.
			 */
			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setStatus("アップロード中...");
			progress.toggleCancel(true, this);
	        document.getElementById("uploadStatus").innerHTML = "ファイルアップロード中です";
		}
		catch (ex) {
			
		}
		
		return true;
	},

	uploadProgress:function (file, bytesLoaded, bytesTotal) {
		try {
			var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setProgress(percent);
			progress.setStatus("アップロード中...");
		} catch (ex) {
			this.debug(ex);
		}
	},


	uploadError:function (file, errorCode, message) {
		try {
			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setError();
			progress.toggleCancel(false);

			switch (errorCode) {
			case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
				progress.setStatus("アップロードエラー: " + message);
				this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
				progress.setStatus("アップロードに失敗しました");
				this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.IO_ERROR:
				progress.setStatus("サーバエラー(I/O)です");
				this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
				progress.setStatus("セキュリティエラー");
				this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
				progress.setStatus("アップロード制限を越えています");
				this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
				progress.setStatus("ファイルチェックに失敗しました。 アップロードをスキップします。");
				this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
				// If there aren't any files left (they were all cancelled) disable the cancel button
				if (this.getStats().files_queued === 0) {
					document.getElementById(this.customSettings.cancelButtonId).disabled = true;
				}
				progress.setStatus("アップロードを全てキャンセル");
				progress.setCancelled();
				break;
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
				progress.setStatus("アップロード中止");
				break;
			default:
				progress.setStatus("不明なエラー: " + errorCode);
				this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
				break;
			}
		} catch (ex) {
	        this.debug(ex);
	    }
	},
	uploadComplete:function (file) {
		//if (this.getStats().files_queued === 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = true;
	        document.getElementById(this.customSettings.uploadButtonId).disabled = true;
//	        document.getElementById('editbutton').disabled = false;
//	        document.getElementById('editbutton').className = "btn-submit";
			document.getElementById(this.customSettings.cancelButtonId).className = "btn-cancel-off";
	        document.getElementById(this.customSettings.uploadButtonId).className = "btn-upload-off";
	        document.getElementById("uploadStatus").innerHTML = "ファイルアップロード完了";
	        pro.todo(pro.sel_prodId,3);
//}
	},
	uploadSuccess:function (file, serverData) {
		try {
	        // disabled upload button
	        this.setButtonDisabled(true);
			var progress = new FileProgress(file, this.customSettings.progressTarget);
			progress.setComplete();
			progress.setStatus("アップロード完了.");
			progress.toggleCancel(false);
			
		} catch (ex) {
			this.debug(ex);
		}
	},
	// This event comes from the Queue Plugin
	queueComplete:function (numFilesUploaded) {
		var status = document.getElementById("divStatus");
	//	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
		status.innerHTML = "アップロードファイル数: " + numFilesUploaded + "枚";
	}
}

var pro = {
	cate_level:0,
	sel_prodId:0,
	upload:null,
	topmenu_id:'#topnav_prod',
	form:{
		_name:'#newpro_form',
		_title:'#newpro_form_title',
		cateroot: '#new_form_cateroot', 
		cates:'.new_form_cate',
		fact:'#new_form_fact',
		name:'#new_form_name',
		model:'#new_form_model',
		info:'#new_form_info',
		size_l:'#new_form_size_l',
		size_w:'#new_form_size_w',
		size_h:'#new_form_size_h',
		weight:'#new_form_weight',
		ok:'#newpro_form_ok',
		id:'#pro_id_hidden',
	},
	item:{
		name:'#pro_name_hidden_',
		model:'#pro_model_hidden_',
		size_l:'#pro_size_l_hidden_',
		size_w:'#pro_size_w_hidden_',
		size_h:'#pro_size_h_hidden_',
		weight:'#pro_weight_hidden_',
		guid:'#pro_guid_hidden_',
		factId:'#pro_factId_hidden_',
		cateId:'#pro_cateId_hidden_',
		info:'#pro_info_hidden_'
	},
	del:{
		_name:"#delpro_form",
		id:'#delete_pro_id'
	},
	image:{
		_name:'#image_form',
		list:'#image_from_list',
	},
	settings:{
	    // Backend Settings
	    flash_url : "<{$ROOTPATH}>/scripts/swfupload/swfupload.swf",
		flash9_url : "<{$ROOTPATH}>/scripts/swfupload/swfupload_fp9.swf",// Relative to this file (or you can use absolute paths)
	    upload_url: "<{$ROOTPATH}>/_manager/pro/upload.php",	// Relative to the SWF file (or you can use absolute paths)
	    post_params : {
	    	"PHPSESSID":"<{$PHPSESSID}>",
	    	"PRODID":0
		},// File Upload Settings
	    file_size_limit : "8192",	// 8MB
	    file_types : "*.jpg",
	    file_types_description : "Jpeg Files",
	    file_upload_limit : 10,
	    file_queue_limit : 0,
	    custom_settings : {
	        progressTarget : "fsUploadProgress",
	        cancelButtonId : "btnCancel",
	        uploadButtonId : "btnUpload"
	    },
	    prevent_swf_caching:true,
	    // Debug Settings
	    debug: false,
	    // Event Handler Settings (all my handlers are in the Handler.js file)
	    swfupload_loaded_handler: swf_upload.swfUploadLoaded,
	    file_queued_handler : swf_upload.fileQueued,
	    file_queue_error_handler : swf_upload.fileQueueError,
	    file_dialog_complete_handler : swf_upload.fileDialogComplete,
	    upload_start_handler : swf_upload.uploadStart,
	    upload_progress_handler : swf_upload.uploadProgress,
	    upload_error_handler :swf_upload.uploadError,
	    upload_success_handler : swf_upload.uploadSuccess,
	    upload_complete_handler : swf_upload.uploadComplete,
	    queue_complete_handler : swf_upload.queueComplete, // Queue plugin event
	    
	    // Button Settings
	    button_image_url: "<{$ROOTPATH}>/images/sys/XPButtonUploadText_61x22.png",
	    button_placeholder_id: "spanButtonPlaceholder",
	    button_width: 250,
	    button_height: 30,
	    button_disabled: false,
	 
	//    // SWFObject settings
	//    minimum_flash_version : "9.0.28",
	    swfupload_pre_load_handler : swf_upload.swfUploadPreLoad,
	    swfupload_load_failed_handler : swf_upload.swfUploadLoadFailed
    },
	init:function(){
		$(this.topmenu_id).attr('class','topmenu_item_thispage');
		
		this.upload = new SWFUpload(this.settings);
	},
	get_images_list:function(id){
		$(pro.image.list).html('');
		$.ajax({
			url:ajax_callback_page,
			data:{
				token:TOKEN_LOAD_IMAGES,
				prodId:id
			},
			success:function(data){
				if(data.ref == 'OK'){
					var html = '';
					for(var i=0;i<data.rows.length;i++){
						html += '<img src="<{$imgpath100}>'+data.rows[i].fileId+'<{$imgextjpg}>" />'
					}
					$(pro.image.list).html(html);
				}else if(data.ref == 'NOIMAGE'){
					$(pro.image.list).html('<span>写真ありません<span>');
				}
			},
			error:function(){
				// blockDesign.defualt('<p>エラー発送しました。<p>','250px');
			},
			beforeSend:function(){
			}
		});
	},
	cate_get_child:function(me,level){
		var cId = $(me).val();
		
		$('#'+me.id + ' + select').remove();
		pro.cate_level = level;
		
		if(cId == 0){
			// do nothing
		}else{
			$.ajax({
				url:ajax_callback_page,
				data:{
					token:TOKEN_LOAD_CATEGORY,
					cateId:cId,
					parent:me.id,
				},
				success:function(data){
					if(data.ref == 'OK'){
						pro.cate_level++;
						var child = 'new_form_cate_'+pro.cate_level;
						$('#'+data.parent).after('<select id="'+child
							+'" class="new_form_cate" onchange="pro.cate_get_child(this,'+pro.cate_level+')">'+
							'<option value="0">選択してください</option></select>');
						for(var i=0;i<data.rows.length;i++){
							$('#'+child).append('<option value="'+data.rows[i].cateId+'">'+
							data.rows[i].name+'</option>');
						}
					}else if(data.ref == 'NOCHILD'){
						
					}
				},
				error:function(){
					// blockDesign.defualt('<p>エラー発送しました。<p>','250px');
				},
				beforeSend:function(){
				}
			});
		}
	},
	todo:function(id,_type){
		if(_type == 0){//update
			var n_form = pro.form;
			var item = pro.item;
			$(n_form.id).val(id);
			$(n_form.name).val($(item.name+id).val());
			$(n_form.model).val($(item.model+id).val());
			$(n_form.size_l).val($(item.size_l+id).val());
			$(n_form.size_w).val($(item.size_w+id).val());
			$(n_form.size_h).val($(item.size_h+id).val());
			$(n_form.weight).val($(item.weight+id).val());
			$(n_form.guid).val($(item.guid+id).val());
			$(n_form.fact).val($(item.factId+id).val());
			$(n_form.info).val($(item.info+id).val());
					
			$(n_form.ok).text('変更して保存');
			$(n_form._title).text('商品を編集する');
			blockDesign.form( $(pro.form._name),'550px','20%','25%');
		}
		<{if $login_adminId == 1}>
		else if(_type == 1){//del
			var d_form = pro.del;
			$.ajax({
				url:ajax_callback_page,
				data:{
					token:TOKEN_DEL_PROD,
					prodId:$(d_form.id).val()
				},
				success:function(data){
					if(data.ref == 'OK'){
						blockDesign.defualt('<p>削除しました。<p>','250px');
					}
				},
				error:function(){
					blockDesign.defualt('<p>エラー発送しました。<p>','250px');
				},
				beforeSend:function(){
				}
			});
		}
		<{/if}>
		else if(_type == 2){//add
			var n_form = pro.form;
			$(n_form._name + ' input').val('');
			$(n_form.ok).text('新規作成');
			$(n_form._title).text('商品を新規作成する');
			$(n_form.id).val(0);
			blockDesign.form( $(pro.form._name),'550px','20%','25%');
		}else if(_type == 3){//images
			this.sel_prodId = id;
			this.get_images_list(id);
			blockDesign.form( $(pro.image._name),'550px','20%','25%');
		}
	},
	update:function(){
		var n_form = pro.form;
		if($(n_form.fact).val() == 0){
			alert('業者様をご選択ください。');
			$(n_form.name).focus();
			return;
		}
		if($(n_form.cates+':last').val() == 0){
			alert('カテゴリをご選択ください。');
			$(n_form.cates+':last').focus();
			return;
		}
		if($(n_form.name).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.name).focus();
			return;
		}
		if($(n_form.model).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.model).focus();
			return;
		}
		if($(n_form.size_l).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_l).focus();
			return;
		}
		if($(n_form.size_w).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_w).focus();
			return;
		}
		if($(n_form.size_h).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_h).focus();
			return;
		}
		if($(n_form.weight).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.weight).focus();
			return;
		}
		// alert($(n_form.cates+':last').val());
		ajaxClicked(this.form.ok);
		$.ajax({
			url:ajax_callback_page,
			data:{
				token:TOKEN_UP_PROD,
				cateId:$(n_form.cates+':last').val(),
				factId:$(n_form.fact).val(),
				name:$(n_form.name).val(),
				model:$(n_form.model).val(),
				info:$(n_form.info).val(),
				size_l:$(n_form.size_l).val(),
				size_w:$(n_form.size_w).val(),
				size_h:$(n_form.size_h).val(),
				weight:$(n_form.weight).val(),
				prodId:$(n_form.id).val()
			},
			success:function(data){
				if(data.ref == 'OK'){
					blockDesign.defualt('<p>更新しました。<p>','250px');
				}
			},
			error:function(){
				//blockDesign.defualt('<p>エラー発送しました。<p>','250px');
			},
			beforeSend:function(){
			}
		});
	},
	add:function(){
		
		var n_form = pro.form;
		if($(n_form.fact).val() == 0){
			alert('業者様をご選択ください。');
			$(n_form.name).focus();
			return;
		}
		if($(n_form.cates+':last').val() == 0){
			alert('カテゴリをご選択ください。');
			$(n_form.cates+':last').focus();
			return;
		}
		if($(n_form.name).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.name).focus();
			return;
		}
		if($(n_form.model).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.model).focus();
			return;
		}
		if($(n_form.size_l).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_l).focus();
			return;
		}
		if($(n_form.size_w).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_w).focus();
			return;
		}
		if($(n_form.size_h).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.size_h).focus();
			return;
		}
		if($(n_form.weight).val() == ''){
			alert('请完整填写所有信息.');
			$(n_form.weight).focus();
			return;
		}
		ajaxClicked(this.form.ok);
		$.ajax({
			url:ajax_callback_page,
			data:{
				token:TOKEN_ADD_PROD,
				cateId:$(n_form.cates+':last').val(),
				factId:$(n_form.fact).val(),
				name:$(n_form.name).val(),
				model:$(n_form.model).val(),
				info:$(n_form.info).val(),
				size_l:$(n_form.size_l).val(),
				size_w:$(n_form.size_w).val(),
				size_h:$(n_form.size_h).val(),
				weight:$(n_form.weight).val()
			},
			success:function(data){
				if(data.ref == 'OK'){
					blockDesign.defualt('<p>新規作成しました。<p>','250px');
				}
			},
			error:function(){
				//blockDesign.defualt('<p>エラー発送しました。<p>','250px');
			},
			beforeSend:function(){
			}
		});
	}
}

